#include <db_sqlite3.h>

#include "misc.h"
#include "db_access.h"
#include "debug.h"

int db_init(sqlite3db_ts *mdb)
{
    if (SQLITE_OK != sqldb_open(DB_FILE, DB_BACKUP_FILE, &(mdb->db)))
    {
        LOGE("sqldb_open error");
        return FAILED;
    }

    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_DEVICE_PROFILE_TABLE_NAME, DB_CREATE_DEVICE_PROFILE_TABLE_SQL))
    {
        LOGE("sqldb_create_table error");
        return FAILED;
    }

    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_ATTR_TABLE_NAME, DB_CREATE_ATTR_TABLE_SQL))
    {
        LOGE("sqldb_create_table error");
        return FAILED;
    }

//    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_DYNAMIC_ATTR_TABLE_NAME, DB_CREATE_DYNAMIC_ATTR_TABLE_SQL))
//    {
//        LOGE( "sqldb_create_table error");
//        return FAILED;
//    }

/*    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_DEV_ATTR_MAP_TABLE_NAME, DB_CREATE_DEV_ATTR_MAP_TABLE_SQL))
    {
        LOGE( "sqldb_create_table error");
        return FAILED;
    }*/

    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_FIRMWARE_TABLE_NAME, DB_CREATE_FIRMWARE_TABLE_SQL))
    {
        LOGE("sqldb_create_table error");
        return FAILED;
    }

    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_VERSION_TABLE_NAME, DB_CREATE_VERSION_TABLE_SQL))
    {
        LOGE("sqldb_create_table error");
        return FAILED;
    }


    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_UNIDEV_TABLE_NAME, DB_UNIDEV_CREATE_UNIDEV_TABLE_SQL))
    {
        LOGE("sqldb_create_table error");
        return FAILED;
    }


    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_DEVICES_TABLE_NAME, DB_CREATE_DEVICES_TABLE_SQL))
    {
        LOGE("sqldb_create_table error");
        return FAILED;
    }


    if (SQLITE_OK != sqldb_create_table(mdb->db, DB_WHITELIST_TABLE_NAME, DB_CREATE_WHITELIST_TABLE_SQL))
    {
        LOGE("sqldb_create_table error");
        return FAILED;
    }


    if (SQLITE_OK != sqldb_save(mdb->db, DB_FILE, DB_BACKUP_FILE))
    {
        LOGE("sqldb_save error");
        return FAILED;
    }

    mdb->modified = false;

    return OK;
}

int db_deinit(sqlite3db_ts *mdb)
{
    int ret = OK;

    if (SQLITE_OK != sqldb_save(mdb->db, DB_FILE, DB_BACKUP_FILE))
    {
        LOGE("sqldb_save error");
        ret = FAILED;
    }

    if (SQLITE_OK != sqldb_close(mdb->db))
    {
        LOGE("sqldb_close error");
        ret = FAILED;
    }

    return ret;
}

int db_save_immediately(sqlite3db_ts *mdb)
{
    if (!mdb->modified)
    {
        return OK;
    }

    LOGI("dbsave db saved");
    if (SQLITE_OK != sqldb_save(mdb->db, DB_FILE, DB_BACKUP_FILE))
    {
        LOGE("dbsave failed");
        return FAILED;
    }

    mdb->modified = false;
    return OK;
}